<template>
  <a-layout>
    <a-layout-content style="padding: 24px;">
      <div class="header">
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link to="/Grant">授权管理</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>
            <a @click="goToExperimentSet">{{ experimentSetName }}</a>
          </a-breadcrumb-item>
          <a-breadcrumb-item>
            <a @click="goToBatch">{{ batchName }}</a>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ experimentName }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>

      <!-- 图片数据表格 -->
      <a-table
          :columns="columns"
          :data-source="imageData"
          :pagination="false"
          :scroll="{ y: '35vh' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'file_size'">
            {{ formatFileSize(record.file_size) }}
          </template>
          <template v-if="column.key === 'metadata'">
            <a-button type="link" @click="showMetadata(record)">查看元数据</a-button>
          </template>
          <template v-if="column.key === 'action'">
            <span>
              <a-button
                  :loading="record.processing"
                  @click="handleViewImage(record)"
              >
                {{ record.processing ? '处理中...' : '查看' }}
              </a-button>
            </span>
          </template>
        </template>
      </a-table>

      <!-- 实验文件表格 -->
      <a-table
          :columns="fileColumns"
          :data-source="fileData"
          :pagination="false"
          :scroll="{ y: '30vh' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'file_size'">
            {{ formatFileSize(record.file_size) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button
                :loading="record.downloading"
                @click="handleDownloadFile(record)"
            >
              {{ record.downloading ? `${record.progress}%` : '下载' }}
            </a-button>
          </template>
        </template>
      </a-table>

      <!-- 元数据抽屉 -->
      <a-drawer
          title="图片元数据"
          placement="right"
          :width="400"
          :visible="metadataDrawerVisible"
          @close="closeMetadataDrawer"
      >
        <template v-if="selectedMetadata">
          <a-descriptions :column="1">
            <a-descriptions-item v-for="(value, key) in selectedMetadata" :key="key" :label="key">
              {{ value }}
            </a-descriptions-item>
          </a-descriptions>
        </template>
      </a-drawer>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import { message } from 'ant-design-vue';
import axiosInstance from '@/axios/axios.js';

export default defineComponent({
  name: 'AuthorizedImage',
  data() {
    return {
      experimentSetName: '',
      batchName: '',
      experimentName: '',
      imageData: [],
      fileData: [],
      metadataDrawerVisible: false,
      selectedMetadata: null,
      columns: [
        {
          title: '图片名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '文件大小',
          dataIndex: 'file_size',
          key: 'file_size'
        },
        {
          title: '类型',
          dataIndex: 'mime_type',
          key: 'mime_type'
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at'
        },
        {
          title: '元数据',
          key: 'metadata',
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          fixed: 'right'
        }
      ],
      fileColumns: [
        {
          title: '文件名',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '文件类型',
          dataIndex: 'file_type',
          key: 'file_type'
        },
        {
          title: '文件大小',
          dataIndex: 'file_size',
          key: 'file_size'
        },
        {
          title: '文件类别',
          dataIndex: 'file_category',
          key: 'file_category'
        },
        {
          title: '操作',
          key: 'action',
          width: 100
        }
      ]
    };
  },
  async created() {
    // 检查登录状态
    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      this.$message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 检查授权信息
    const userAddress = this.$cookies.get("userAddress");
    const accessId = this.$route.query.accessId;
    if (!userAddress || !accessId) {
      this.$message.error('授权信息不完整');
      this.$router.push('/Grant');
      return;
    }

    try {
      console.log('Route query params:', this.$route.query);
      
      // 从路由参数中获取数据
      const { experimentSetName, batchName, experimentName, imageData, experimentId, allData: allDataStr } = this.$route.query;
      
      // 验证必要的参数
      if (!imageData || !experimentId) {
        throw new Error('缺少必要的参数');
      }

      // 解析原始allData，查看完整的数据结构
      const originalAllData = JSON.parse(allDataStr || '{}');
      console.log('Original allData from Grant.vue:', {
        experimentSets: originalAllData.experimentSets?.length,
        batches: originalAllData.batches?.length,
        experiments: originalAllData.experiments?.length,
        images: originalAllData.images?.map(img => ({
          name: img.name,
          table_type: img.table_type,
          path: img.path
        }))
      });

      this.experimentSetName = experimentSetName || '未知实验集';
      this.batchName = batchName || '未知批次';
      this.experimentName = experimentName || '未知实验';

      // 解析图片数据和allData
      let parsedImageData;
      let allData;
      try {
        parsedImageData = JSON.parse(imageData);
        allData = JSON.parse(allDataStr || '{}');
      } catch (error) {
        console.error('JSON解析错误:', error);
        throw new Error('数据格式不正确');
      }

      console.log('数据加载:', {
        experimentSetId: this.$route.query.experimentSetId,
        batchId: this.$route.query.batchId,
        experimentId: this.$route.query.experimentId,
        accessId: this.$route.query.accessId,
        imageCount: parsedImageData.length
      });

      // 使用传递过来的数据，保持URL不变
      this.imageData = parsedImageData.map(img => {
        console.log('Processing image:', img);

        console.log('Processing image data:', {
          name: img.name,
          table_type: img.table_type,
          original_path: img.path,
          relative_path: img.relative_path,
          tx_hash: img.tx_hash
        });

        // 保留原始path，不做处理
        const originalPath = img.path;
        console.log('Image path info:', {
          name: img.name,
          table_type: img.table_type,
          path: originalPath
        });

        // 查找对应的experimentFile
        const experimentFile = allData.experimentFiles?.find(file =>
          file.name === img.name && file.reference_id === this.$route.query.experimentId
        );

        // 合并元数据
        const metadata = {
          width: experimentFile?.width || img.width,
          height: experimentFile?.height || img.height,
          colorSpace: experimentFile?.colorSpace || img.colorSpace,
          colorType: experimentFile?.colorType || img.colorType,
          fileSize: experimentFile?.file_size || img.file_size,
          created_at: experimentFile?.created_at || img.created_at,
          file_type: experimentFile?.file_type || img.file_type,
          file_category: experimentFile?.file_category || img.file_category,
          reference_type: experimentFile?.reference_type || img.reference_type,
          image_width: experimentFile?.width ? `${experimentFile.width} pixels` : undefined,
          image_height: experimentFile?.height ? `${experimentFile.height} pixels` : undefined
        };

        // 保持原始数据不变，只添加UI所需字段
        const processedImg = {
          ...img,  // 保留所有原始字段
          key: img.file_id || img.image_id || img._temp_comment,
          name: img.name || '未命名图片',
          processing: false,
          experiment_set_id: img.experiment_set_id || this.$route.query.experimentSetId,
          batch_id: img.batch_id || this.$route.query.batchId,
          experiment_id: img.experiment_id || this.$route.query.experimentId,
          path: originalPath,  // 保留原始完整路径
          metadata: metadata,  // 添加合并后的元数据
          tx_hash: img.tx_hash  // 保留tx_hash字段
        };

        console.log('Processed image data:', {
          original: img,
          processed: processedImg,
          query: this.$route.query
        });

        console.log('Processed image with IDs:', {
          experiment_set_id: processedImg.experiment_set_id,
          batch_id: processedImg.batch_id,
          experiment_id: processedImg.experiment_id,
          from_route: {
            experimentSetId: this.$route.query.experimentSetId,
            batchId: this.$route.query.batchId,
            experimentId: this.$route.query.experimentId
          }
        });
        console.log('Processed image:', processedImg);
        return processedImg;
      });

      console.log('Processed image data:', this.imageData);

      // 初始化实验文件数据
      try {
        const allData = JSON.parse(this.$route.query.allData || '{}');
        const experimentFiles = allData.experimentFiles || [];
        const currentExperimentId = this.$route.query.experimentId;
        this.fileData = experimentFiles
            .filter(file => file.reference_id === currentExperimentId)
            .map(file => ({
              ...file,
              key: file.file_id || file._temp_comment,
              downloading: false,
              progress: 0
            }));
        console.log('Processed file data:', this.fileData);
      } catch (error) {
        console.error('解析文件数据失败:', error);
        message.error('解析文件数据失败');
        this.fileData = [];
      }
    } catch (error) {
      console.error('解析图片数据失败:', error);
      message.error('解析图片数据失败');
      this.imageData = [];
      this.fileData = [];
    }
  },
  methods: {
    async handleDownloadFile(record) {
      if (!record || !record.name) {
        message.error('无效的文件数据');
        return;
      }

      if (record.downloading) {
        message.warning('文件正在下载中');
        return;
      }

      // 更新文件状态
      const index = this.fileData.findIndex(f => f.file_id === record.file_id);
      if (index !== -1) {
        this.fileData[index].downloading = true;
        this.fileData[index].progress = 0;
      }

      try {
        // 验证文件记录
        if (!record.file_id) {
          throw new Error('文件ID不存在');
        }

        // 获取授权信息
        const userAddress = this.$cookies.get("userAddress");
        const accessId = this.$route.query.accessId;
        if (!userAddress || !accessId) {
          throw new Error('授权信息不完整');
        }

        // 处理文件路径
        let filePath;
        if (record.table_type === 'image' && record.path) {
          // 对于image类型的数据，从完整路径中提取相对路径部分
          // 去掉/root/data/和用户名/实验集名前缀
          const pathParts = record.path.split('/');
          // 跳过 ["", "root", "data", "test1", "testsample1"]，取后面的部分
          filePath = pathParts.slice(5).join('/');
          console.log('Extracted relative path from file path:', {
            originalPath: record.path,
            extractedPath: filePath
          });
        } else {
          // 使用已有的relative_path或构造新路径
          filePath = record.relative_path;
          if (!filePath) {
            console.warn('File missing relative_path, constructing path:', record);
            filePath = `${this.batchName}/${this.experimentName}/Images/${record.name}`;
          }
        }

        console.log('File path:', {
          name: record.name,
          original_path: record.relative_path,
          constructed_path: filePath
        });

        const sharedPath = `shared/${userAddress}/${accessId}/${filePath}`;
        const encodedPath = encodeURIComponent(sharedPath);

        console.log('开始下载文件:', {
          name: record.name,
          path: sharedPath
        });

        const response = await axiosInstance({
          method: "GET",
          url: `/download/file?relativePath=${encodedPath}`,
          responseType: "blob",
          timeout: 300000, // 5分钟超时
          headers: {
            Authorization: `Bearer ${this.$cookies.get('jwt')}`,
            'Cache-Control': 'no-cache',  // 防止缓存
            'Pragma': 'no-cache'
          },
          withCredentials: true,  // 确保发送cookies
          onDownloadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              if (index !== -1) {
                this.fileData[index].progress = progress;
              }
            }
          }
        });

        if (!response.data || response.data.size === 0) {
          throw new Error('未收到文件数据');
        }

        // 获取文件类型
        const contentType = response.headers['content-type'] || 'application/octet-stream';
        const blob = new Blob([response.data], { type: contentType });

        // 创建下载链接
        const blobUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.setAttribute('download', record.name);
        
        // 添加到文档并触发下载
        document.body.appendChild(link);
        link.click();
        
        // 清理
        setTimeout(() => {
          link.remove();
          window.URL.revokeObjectURL(blobUrl);
        }, 100);

        message.success('下载完成');
      } catch (error) {
        console.error('下载文件失败:', error);
        message.error(error.message || '下载失败，请重试');
      } finally {
        // 重置文件状态
        if (index !== -1) {
          this.fileData[index].downloading = false;
          this.fileData[index].progress = 0;
        }
      }
    },
    formatFileSize(bytes) {
      if (!bytes) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    goToExperimentSet() {
      this.$router.go(-2);
    },
    goToBatch() {
      this.$router.go(-1);
    },
    showMetadata(record) {
      try {
        console.log('Showing metadata for record:', record);
        let metadata = record.metadata;
        console.log('Raw metadata:', metadata);
        console.log('Record data:', {
          record,
          metadata: record.metadata,
          colorSpace: record.colorSpace,
          colorType: record.colorType,
          fileSize: record.file_size,
          created_at: record.created_at,
          file_type: record.file_type,
          file_category: record.file_category,
          reference_type: record.reference_type,
          tx_hash: record.tx_hash,
          file_hash: record.file_hash
        });

        // 解析元数据字符串
        let parsedMetadata = {};
        if (typeof metadata === 'string' && metadata.trim()) {
          try {
            parsedMetadata = JSON.parse(metadata);
          } catch (e) {
            console.warn('Failed to parse metadata string:', e);
          }
        } else if (metadata && typeof metadata === 'object') {
          parsedMetadata = metadata;
        }

        // 合并所有可能的元数据来源
        metadata = {
          ...parsedMetadata,
          width: record.width || parsedMetadata.width,
          height: record.height || parsedMetadata.height,
          pixelSize: record.pixelSize || parsedMetadata.pixelSize,
          colorType: record.colorType || parsedMetadata.colorType,
          colorSpace: record.colorSpace || parsedMetadata.colorSpace,
          y_resolution: record.y_resolution || parsedMetadata.y_resolution,
          image_width: record.image_width || parsedMetadata.image_width,
          image_height: record.image_height || parsedMetadata.image_height,
          created_at: record.created_at || parsedMetadata.created_at,
          file_hash: record.file_hash || parsedMetadata.file_hash,
          file_size: record.file_size || parsedMetadata.file_size,
          mime_type: record.mime_type || parsedMetadata.mime_type,
          file_type: record.file_type || parsedMetadata.file_type,
          file_category: record.file_category || parsedMetadata.file_category,
          reference_type: record.reference_type || parsedMetadata.reference_type,
          tx_hash: record.tx_hash || parsedMetadata.tx_hash
        };
        console.log('Combined metadata:', metadata);

        // 使用record.metadata中的数据
        const basicInfo = {
          '文件名': record.name || '未知',
          '文件类型': record.metadata?.file_type || record.mime_type || '未知',
          '文件大小': record.metadata?.fileSize ? this.formatFileSize(record.metadata.fileSize) : '未知',
          '创建时间': record.metadata?.created_at || '未知',
          'Hash': record.tx_hash || '未知',
          '引用ID': record.reference_id || '未知',
          '引用类型': record.metadata?.reference_type || '未知',
          '图片宽度': record.metadata?.image_width || '未知',
          '图片高度': record.metadata?.image_height || '未知',
          '颜色空间': record.metadata?.colorSpace || '未知',
          '颜色类型': record.metadata?.colorType || '未知',
          '文件类别': record.metadata?.file_category || '未知'
        };

        // 移除undefined或null的字段
        Object.keys(basicInfo).forEach(key => {
          if (basicInfo[key] === undefined || basicInfo[key] === null) {
            delete basicInfo[key];
          }
        });

        // 合并基本信息和其他metadata字段
        this.selectedMetadata = {
          ...basicInfo,
          ...Object.keys(metadata)
              .filter(key => !Object.keys(basicInfo).includes(key))
              .reduce((obj, key) => {
                if (metadata[key] !== undefined && metadata[key] !== null) {
                  obj[key] = metadata[key];
                }
                return obj;
              }, {})
        };
        console.log('Final metadata with basic info:', this.selectedMetadata);
        this.metadataDrawerVisible = true;
      } catch (error) {
        console.error('解析元数据失败:', error);
        message.error('解析元数据失败');
      }
    },
    closeMetadataDrawer() {
      this.metadataDrawerVisible = false;
      this.selectedMetadata = null;
    },

    async handleViewImage(image) {
      if (!image || !image.name) {
        message.error('无效的图片数据');
        return;
      }

      console.log('处理图片查看:', image.name);
      let index = -1;

      try {
        // 处理图片路径
        let imagePath;
        if (image.table_type === 'image' && image.path) {
          // 对于image类型的数据，从完整路径中提取相对路径部分
          // 去掉/root/data/和用户名/实验集名前缀
          const pathParts = image.path.split('/');
          // 跳过 ["", "root", "data", "test1", "testsample1"]，取后面的部分
          imagePath = pathParts.slice(5).join('/');
          console.log('Extracted relative path from image path:', {
            originalPath: image.path,
            extractedPath: imagePath
          });
        } else {
          // 使用已有的relative_path或构造新路径
          imagePath = image.relative_path;
          if (!imagePath) {
            console.warn('No path available, constructing fallback path:', image);
            imagePath = `${this.batchName}/${this.experimentName}/Images/${image.name}`;
          }
        }

        console.log('Final image path:', {
          name: image.name,
          table_type: image.table_type,
          original_path: image.path,
          relative_path: image.relative_path,
          final_path: imagePath
        });

        // 更新图片状态
        index = this.imageData.findIndex(img => img.name === image.name);
        if (index !== -1) {
          this.imageData[index].processing = true;
        }

        // 检查并设置必要字段
        const processedImage = {
          ...image,
          experiment_set_id: image.experiment_set_id || this.$route.query.experimentSetId,
          batch_id: image.batch_id || this.$route.query.batchId,
          experiment_id: image.experiment_id || this.$route.query.experimentId
        };

        // 验证必要的ID
        if (!processedImage.experiment_set_id || !processedImage.batch_id || !processedImage.experiment_id) {
          throw new Error('缺少必要的实验信息');
        }

        // 获取授权信息
        const userAddress = this.$cookies.get("userAddress");
        const accessId = this.$route.query.accessId;
        if (!userAddress || !accessId) {
          throw new Error('授权信息不完整');
        }

        // 构造共享路径
        const sharedPath = `shared/${userAddress}/${accessId}/${imagePath}`;
        const encodedPath = encodeURIComponent(sharedPath);
        
        console.log('请求图片:', {
          name: image.name,
          path: sharedPath
        });

        // 请求图片数据
        const response = await axiosInstance({
          method: 'GET',
          url: `/download/file?relativePath=${encodedPath}`,
          responseType: 'blob',
          timeout: 30000, // 30秒超时
          headers: {
            Authorization: `Bearer ${this.$cookies.get('jwt')}`,
            'Cache-Control': 'no-cache',  // 防止缓存
            'Pragma': 'no-cache'
          },
          withCredentials: true  // 确保发送cookies
        });

        if (!response.data || response.data.size === 0) {
          throw new Error('未收到图片数据');
        }

        // 从response headers获取MIME类型
        const contentType = response.headers['content-type'] || this.getMimeType(image.name);
        const blob = new Blob([response.data], { type: contentType });

        // 转换为base64
        await new Promise((resolve, reject) => {
          const reader = new FileReader();
          
          reader.onloadend = () => {
            try {
              const base64data = reader.result;
              if (!base64data) {
                reject(new Error('base64转换失败'));
                return;
              }

              // 确保base64数据格式正确
              const base64WithMime = base64data.startsWith('data:')
                ? base64data
                : `data:${contentType};base64,${base64data.split(',')[1] || base64data}`;

              // 验证base64数据
              if (!this.isValidBase64Image(base64WithMime)) {
                reject(new Error('生成的图片数据无效'));
                return;
              }

              console.log('Preparing image data for detail view:', {
                original_image: image,
                processed_image: processedImage,
                path: image.path,
                relative_path: imagePath
              });

              // 构建查询参数
              const queryParams = {
                imgUrl: base64WithMime,
                imgUrlFortif: base64WithMime,
                experimentSetId: processedImage.experiment_set_id,
                batchId: processedImage.batch_id,
                experimentId: processedImage.experiment_id,
                metadata: JSON.stringify({
                  width: image.width,
                  height: image.height,
                  colorSpace: image.colorSpace,
                  colorType: image.colorType,
                  fileSize: image.file_size,
                  created_at: image.created_at,
                  file_type: image.file_type,
                  file_category: image.file_category,
                  reference_type: image.reference_type,
                  image_width: image.width ? `${image.width} pixels` : undefined,
                  image_height: image.height ? `${image.height} pixels` : undefined,
                  tx_hash: image.tx_hash,
                  path: image.path  // 添加原始path到metadata
                }),
                tx_hash: image.tx_hash,
                hash: image.tx_hash,
                path: image.path,  // 添加原始完整路径
                relative_path: imagePath,  // 添加处理后的相对路径
                accessId: this.$route.query.accessId,  // 添加accessId参数
                username: image.path.split('/')[3]  // 从path中提取username
              };
    
              console.log('Detail view parameters:', {
                metadata: JSON.parse(queryParams.metadata),
                tx_hash: queryParams.tx_hash,
                path: queryParams.path,
                relative_path: queryParams.relative_path
              });

              // 导航到详情页
              this.$router.push({
                path: '/detail',
                query: queryParams
              });

              resolve();
            } catch (error) {
              reject(error);
            }
          };

          reader.onerror = () => reject(new Error('读取文件失败'));
          reader.readAsDataURL(blob);
        });

      } catch (error) {
        console.error('图片处理失败:', error);
        message.error(error.message || '处理图片时发生错误');
      } finally {
        // 重置图片状态
        if (index !== -1) {
          this.imageData[index].processing = false;
        }
      }
    },

    // 获取文件的MIME类型
    getMimeType(filename) {
      const ext = filename.split('.').pop().toLowerCase();
      const mimeTypes = {
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'tif': 'image/tiff',
        'tiff': 'image/tiff'
      };
      return mimeTypes[ext] || 'application/octet-stream';
    },

    // 验证base64图片数据
    isValidBase64Image(base64String) {
      if (!base64String || typeof base64String !== 'string') {
        return false;
      }
      
      // 检查是否包含正确的头部
      if (!base64String.startsWith('data:image/')) {
        return false;
      }

      // 检查base64部分是否存在
      const base64Data = base64String.split(',')[1];
      if (!base64Data) {
        return false;
      }

      // 检查base64字符串长度
      if (base64Data.length < 100) { // 假设有效的图片base64至少100字符
        return false;
      }

      return true;
    }
  }
});
</script>

<style scoped>
.header {
  margin-bottom: 24px;
}
</style>